package com.lst.servlet;

import java.io.File;
import java.io.PrintWriter;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.druid.util.StringUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lst.base.entity.BaseRequest;
import com.lst.base.entity.BaseResponse;
import com.lst.common.CommCode;
import com.lst.common.CommFun;
import com.lst.dao.ResourcesMapper;
import com.lst.entity.request.QuestionReqPara;
import com.lst.model.Question;
import com.lst.model.Resources;
import com.lst.service.QuestionService;
import com.lst.utils.CommonUtils;
import com.lst.utils.DateUtil;
import com.lst.utils.RequestUtils;
import com.lst.utils.SensitiveUtil;


/**
 * @ClassName: QuestionAddServlet
 * @Description: 问题添加接口
 * 
 */
public class QuestionAddServlet extends BaseServlet {

	/**
	 * @Fields serialVersionUID
	 */
	private static final long serialVersionUID = 1L;

	private QuestionService questionService = ctx.getBean(QuestionService.class);
	
	private ResourcesMapper resourcesMapper = ctx.getBean(ResourcesMapper.class);
	
	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		doPost(request, response);
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) {
		Date startDate = new Date();
		logger.info("doPost begin: " + startDate);
		BaseResponse resPara = new BaseResponse();

		try {
			QuestionReqPara reqPara = getReqPara(request);
		
		if(isCheckField(reqPara,resPara)){
			Integer userid = Integer.valueOf(reqPara.getUserid());
			String questionTitle = reqPara.getQuestionTitle();					
			String questionContent = reqPara.getQuestionContent();
			String pictureUrl = reqPara.getPictureUrl();
			Integer questionType = Integer.valueOf(reqPara.getQuestionType());
			Integer recordId = StringUtils.isEmpty(reqPara.getRecordId())?0:Integer.valueOf(reqPara.getRecordId());
			
//			String str1=SensitiveUtil.check(questionTitle);
//			String str2=SensitiveUtil.check(questionContent);
//		    if((str1.length()==2&&str2.length()==2) || (str1==""&&str2=="")){
		    	String picUrl = "";
				if(!StringUtils.isEmpty(pictureUrl)){
					List<String> urls = dealImgs(pictureUrl, startDate, userid);
					picUrl = urls.get(0);
					if(urls!=null&&urls.size()>0){
						for(int i=1;i<urls.size();i++){
							picUrl=picUrl+","+urls.get(i);
						}
					}
					
				}
				
				Question md = new Question();
				
				md.setCreateUser(userid);
		        md.setQuestionTitle(questionTitle);
		        md.setQuestionContent(questionContent);
		        md.setPictureUrl(picUrl);
		        md.setQuestionType(questionType);
		        md.setRecordId(recordId);
				md.setCreateDate(startDate);
				
				questionService.insert(md);
				
				resPara.setCode(CommCode.M_Y000000);
				resPara.setMessage(CommCode.M_Y000001);
//		    }else{
//		    	resPara.setCode(CommCode.M_A000000);
//				resPara.setMessage("标题或者描述里含有违禁词，请修改");
//		    }
			
			
		  }
		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0001);

			logger.error("doPost error: ", e);
		}
		
		try {
			response.setContentType("application/json;charset=utf-8");
			response.setHeader("pragma", "no-cache");
			response.setHeader("cache-control", "no-cache");

			Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").excludeFieldsWithoutExposeAnnotation().serializeNulls().create();
			String jsonResult = gson.toJson(resPara);
			logger.info("QuestionAddServlet jsonResult:" + jsonResult);

			PrintWriter out = response.getWriter();
			out.print(jsonResult);
			out.flush();
			out.close();

			logger.info("doPost end run(s): " + DateUtil.calLastedTime(startDate));
		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0003);

			logger.error("doPost error: ", e);
		}
	}

	@Override
	public QuestionReqPara getReqPara(HttpServletRequest request) {

		QuestionReqPara reqPara = null;

		try {
			BaseRequest baseRequest = RequestUtils.getRequestPara(request, new QuestionReqPara());

			reqPara = (QuestionReqPara) baseRequest.clone();

			String userid = request.getParameter("userid");
			String questionTitle = request.getParameter("questionTitle");
			String questionContent = request.getParameter("questionContent");
			String pictureUrl = request.getParameter("pictureUrl");
			String recordId = request.getParameter("recordId");
			String questionType = request.getParameter("questionType");
	
			
			logger.info("reqPara userid:" + userid);
			logger.info("reqPara questionTitle: " + questionTitle);
			logger.info("reqPara questionContent: " + questionContent);
			logger.info("reqPara pictureUrl:" + pictureUrl);
			logger.info("reqPara recordId:" + recordId);
			logger.info("reqPara questionType:" + questionType);
			
	        reqPara.setQuestionTitle(questionTitle);
	        reqPara.setQuestionContent(questionContent);
	        reqPara.setPictureUrl(pictureUrl);
	        reqPara.setUserid(userid);
	        reqPara.setQuestionType(questionType);
	        reqPara.setRecordId(recordId);

		} catch (Exception e) {
			logger.error("getReqPara error: ", e);
		}

		return reqPara;
	}

	@Override
	public boolean isCheckField(BaseRequest reqPara, BaseResponse resPara) {
		boolean flag = false;

		QuestionReqPara cdReqPara = (QuestionReqPara) reqPara;
		BaseResponse cdResPara = (BaseResponse) resPara;

		if (StringUtils.isEmpty(cdReqPara.getQuestionTitle())) {
			cdResPara.setCode(CommCode.M_A000000);
			cdResPara.setMessage("问题标题为空");
		} else if (StringUtils.isEmpty(cdReqPara.getUserid())) {
			cdResPara.setCode(CommCode.M_A000000);
			cdResPara.setMessage(CommCode.M_P000002);
		}else if (StringUtils.isEmpty(cdReqPara.getRecordId())) {
			cdResPara.setCode(CommCode.M_A000000);
			cdResPara.setMessage("训练记录id为空");
		}else if (StringUtils.isEmpty(cdReqPara.getQuestionType())) {
			cdResPara.setCode(CommCode.M_A000000);
			cdResPara.setMessage("问题类型为空");
		} else {
			flag = true;
		}

		return  flag;
	}
	
	/**
	 * 
	 * @Title: dealImgs
	 * @Description: 处理图片集 
	 * @param @param portrait  
	 * @param @param startDate
	 * @param @param mstClient
	 * @param @return
	 * @param @throws ParseException    设定文件
	 * @return List<String>    返回类型
	 */
	private synchronized List<String> dealImgs(String portrait,Date startDate,Integer userId) throws ParseException{
		//以逗号分分割多张图片
		String [] portraits = portrait.split(",");
		//存放“文件夹 + 图片名称”集
		List<String> urls = new ArrayList<String>();
		//图片资源集
		List<Resources> mstResources = new ArrayList<Resources>();
		//获取时分秒文件夹地址
		String timeAddr = DateUtil.getCurrentTime(DateUtil.ALL_DATE_HORIZONTAL);
		//获取工厂地址
		String facAddr = CommonUtils.getImg_file_path_linux() + timeAddr;

		// 创建工厂文件
		File facFile = new File(facAddr);
		if (!facFile.exists()) {
			facFile.mkdirs();
		}

		String imgName = "";// 图片名称
		String absPath = "";//文件绝对路径
		String relPath = "";//文件相对路径

		// 批量保存图片
		int len = portraits.length;
		for (int i = 0; i < len; i++) {

			imgName = DateUtil
					.getCurrentTime(DateUtil.ALL_DATETIME_STRING_QUEUE)
					+ i;

			absPath = facAddr + "/"+ imgName;

			CommFun.base64StringToImage4One2(
					portraits[i], absPath);

			relPath = CommCode.RESOURCE_URL_IMAGE + timeAddr +"/"+imgName + ".jpg";
			urls.add(relPath);

			Resources resource = new Resources();
			resource.setCreatedate(startDate);
			resource.setCreateuser(userId);
			resource.setEnabled(true);
			resource.setExtname(".jpg");
			resource.setIsdeleted(false);
			resource.setResname(imgName);
			resource.setRespath(CommCode.RESOURCE_URL_IMAGE + timeAddr +"/");
			resource.setOrderindex(i);
			resource.setOwnerid(userId);
			resource.setOwnertablename("MST_CLIENT");
			resource.setRestype(CommCode.SYSCODE_REOURCES_TYPE_IMAGE);

			mstResources.add(resource);

			logger.info("decPara absPath : " + absPath + "and the index :" + i);
			logger.info("decPara relPath : " + relPath + "and the index :" + i);
		}

		resourcesMapper.saveList(mstResources);

		return urls;

	}

}
